package Thread2;

// 通过懒汉模式构造单例模式

class SingletonLazy2{
    private static volatile SingletonLazy2 instance = null;
    /*volatile 的功能有两个方面
     1.确保每次读取操作,都是读内存
     2.关于该变量的读取和修改操作不是触发重排序
    */
    private static Object locker = new Object();
    public static SingletonLazy2 getInstance(){
        if(instance == null){ // 判定是否需要加锁
            synchronized (locker){
                if(instance == null){ // 判定是否需要new 对象
                    instance = new SingletonLazy2();
                }
            }
        }
        return instance;
    }
    private SingletonLazy2(){

    }
}

class SingletonLazy{
    private static SingletonLazy instance = null;
    public static SingletonLazy getInstance(){
        if(instance == null){
            instance = new SingletonLazy();
        }
        return instance;
    }
    private SingletonLazy(){

    }
}

public class Demo27 {
    public static void main(String[] args) {
        SingletonLazy t1 = SingletonLazy.getInstance();
        SingletonLazy t2 = SingletonLazy.getInstance();
        System.out.println(t1 == t2);

        // SingletonLazy t3 = new SingletonLazy();
    }
}
